package net.godcode.t5c.components;

import net.godcode.t5c.mixins.RenderNode;

import org.apache.tapestry.MarkupWriter;
import org.apache.tapestry.TapestryConstants;
import org.apache.tapestry.annotations.BeginRender;
import org.apache.tapestry.annotations.Mixin;
import org.apache.tapestry.annotations.Parameter;
import org.apache.tapestry.annotations.SetupRender;
import org.apache.tapestry.annotations.SupportsInformalParameters;
import org.apache.tapestry.corelib.mixins.DiscardBody;
import org.apache.tapestry.corelib.mixins.RenderInformals;

@SupportsInformalParameters
/**
 * Truncate text and append a suffix indicating the truncation. Typically this
 * is done to display segments of text such as articles, followed by a
 * "..." and a link to the full article.
 * 
 * @author Chris Lewis Dec 26, 2007 <chris@thegodcode.net>
 * @version $Id: Truncate.java 85 2008-01-03 21:53:46Z burningodzilla $
 * @since 0.2.0
 */
public class Truncate {
	
	/** The text to be truncated. */
	@Parameter(required = true)
	private String text;
	
	/** The maximum allowed length. */
	@Parameter(required = true)
	private int length;
	
	/** The suffix. */
	@Parameter(value = "...", defaultPrefix = TapestryConstants.LITERAL_BINDING_PREFIX)
	private String suffix;
	
	@SuppressWarnings("unused")
	@Mixin
	private RenderInformals renderInformals;
	
	@SuppressWarnings("unused")
	@Mixin
	private DiscardBody discardBody;
	
	@SuppressWarnings("unused")
	@Mixin
	private RenderNode renderNode;
	
	private String truncatedText;
	
	@SetupRender
	void setupRender() {
		truncatedText = text.length() > length ? text.substring(0, length - suffix.length()) + suffix : text;
	}
	
	/*
	 * TODO This is monkey work and should be handled by a mixin. It's probably
	 * common enough for a component to be able to render as a text node or
	 * in an element.
	 */
	
	@BeginRender
	void beginRender(MarkupWriter writer) {
		writer.write(truncatedText);
	}
	
}
